﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NCC_SOP.app_codes;

namespace NCC_SOP.Admin.AdministratorOnly
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                initBind();
                MultiView1.ActiveViewIndex = 0;
            }
        }

        //To populate the UserNames into Users(CheckBoxList)
        protected void initBind()
        {
            dbConnection db = new dbConnection();
            try
            {
                Users.DataSource = db.getAllUsers();
                Users.DataBind();
            }
            catch (Exception e) 
            {
                Session["ErrorMessage"] = e.Message;
                Response.Redirect("~/ErrorDisplayPage.aspx");
            }
        }

        //To create role with the selected users
        protected void CreateRole(object sender, EventArgs e)
        {
            CustomValidator1.Validate();
            try
            {
                if (Page.IsValid)
                {
                    dbConnection db = new dbConnection();
                    string[] userNames = retrieveFunctions.getSelectedItems(Users);
                    string role = RoleName.Text;
                    db.createNewRole(role);
                    db.addUsersIntoReportRole(userNames, role);
                    
                    //MultiView index 1 shows a Success Message.
                    MultiView1.ActiveViewIndex = 1;
                }
            }
            catch (Exception e1)
            {
                Session["ErrorMessage"] = e1.Message;
                Response.Redirect("~/ErrorDisplayPage.aspx");
            }
        }

        //To check for conflicting role names
        protected void CheckRoleExists(object source, ServerValidateEventArgs args)
        {
            args.IsValid = true;
            try
            {
                dbConnection db = new dbConnection();
                if (db.roleExists(RoleName.Text))
                {
                    args.IsValid = false;
                }
            }
            catch (Exception e)
            {
                Session["ErrorMessage"] = e.Message;
                Response.Redirect("~/ErrorDisplayPage.aspx");
            }
        }

        protected void RedirectToHomePage(object sender, EventArgs e)
        {
            Response.Redirect("~/Default.aspx");
        }
    }
}